package com.lizhanglong.core;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class HttpHelper {
    protected void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new MyTrustManager();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }


    public boolean isTrustAllHttpsCertificates() {
        return isTrustAllHttpsCertificates;
    }

    public void setTrustAllHttpsCertificates(boolean trustAllHttpsCertificates) {
        isTrustAllHttpsCertificates = trustAllHttpsCertificates;
    }

    public int getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public String getCharSet() {
        return charSet;
    }

    public void setCharSet(String charSet) {
        this.charSet = charSet;
    }

    public String getReferer() {
        return referer;
    }

    public void setReferer(String referer) {
        this.referer = referer;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public boolean isTrustAllHttpsCertificates;
    private int readTimeout = 30000;
    private int connectTimeout = 10000;
    private String charSet = "utf-8";
    private String referer = null;
    private String tag = "HttpHelper";


    public String httpGet(String url) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        String result = "";
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        httpURLConnection.setRequestMethod("GET");

        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == 200) {
            result = getInputStreamString(httpURLConnection.getInputStream(), charSet);
        } else {
            System.out.println("http ResponseCode：" + httpURLConnection.getResponseCode());
        }
        httpURLConnection.disconnect();
        return result;
    }


    public String httpPost(String url, String data)
            throws IOException, NoSuchAlgorithmException, KeyManagementException {
        String result = "";
        URL url2 = new URL(url);
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDefaultUseCaches(false);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        if (data != null && data.length() > 0) {
            byte[] b = data.getBytes(charSet);
            httpURLConnection.setRequestProperty("Content_Length", Integer.toString(b.length));
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(b);
            outputStream.flush();
            outputStream.close();
        } else {
            httpURLConnection.connect();
        }
        if (httpURLConnection.getResponseCode() == 200) {
            result = getInputStreamString(httpURLConnection.getInputStream(), charSet);
            // System.out.println("http result:" + result);
        } else {
            System.err.println("http result:" + httpURLConnection.getResponseMessage());
            // System.out.println("http ResponseCode：" +
            // httpURLConnection.getResponseCode());
        }
        httpURLConnection.disconnect();
        return result;
    }


    public String getInputStreamString(InputStream inputStream, String charSet)
            throws IOException {
        String result;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] tmpByte = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(tmpByte)) != -1) {
            byteArrayOutputStream.write(tmpByte, 0, len);
        }
        result = byteArrayOutputStream.toString(charSet);
        byteArrayOutputStream.close();
        return result;
    }

    /**
     * @param url            地址
     * @param connectTimeout (秒)
     * @return
     * @throws Exception
     */
    public int getUrlResponseCode(String url, int connectTimeout) throws Exception {
        if (connectTimeout < 10) {
            connectTimeout = 10000;
        } else if (connectTimeout > 60) {
            connectTimeout = 60000;
        }
        URL url2 = new URL(url + "?i=" + System.currentTimeMillis());
        HttpURLConnection httpURLConnection = (HttpURLConnection) url2.openConnection();
        httpURLConnection.setConnectTimeout(connectTimeout * 1000);
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();
        int code = httpURLConnection.getResponseCode();
        httpURLConnection.disconnect();
        return code;
    }

    /**
     * 创建http请求（未打开连接，只设置了基本属性）
     *
     * @param urlString
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public HttpURLConnection getHttpURLConnection(String urlString)
            throws MalformedURLException, IOException, KeyManagementException, NoSuchAlgorithmException {
        URL url = new URL(urlString);
        if (isTrustAllHttpsCertificates) {
            trustAllHttpsCertificates();
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    Log.i(tag, "Warning: URL Host: " + urlHostName + " vs. " + session
                            .getPeerHost());
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        }
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(connectTimeout);
        httpURLConnection.setReadTimeout(readTimeout);
        httpURLConnection.setRequestProperty("Charset", charSet);
        httpURLConnection.setRequestProperty("referer", referer);
        return httpURLConnection;
    }
}
